<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回到顶部</title>
    <style>
        .back-top {
            height: 92px;
            width: 84px;
            position: fixed;
            display: flex;
            flex-direction: column;
            align-items: center;
            right: 0px;
            bottom: 100px;
        }

        img {
            height: 30px;
            width: 30px;
            margin-top: 18px;
        }

        span {
            font-size: 14px;
            margin-top: 10px;
            color: #757575;
        }

        .back-top:hover {
            cursor: pointer;
        }

        .back-top:hover span {
            color: #ff6700;
        }

        .hide {
            display: none;
        }
    </style>
</head>

<body>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>长</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>江</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>二</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <h1>桥</h1>
    <div class="back-top hide">
        <img src="./images/totop.png">
        <span>回顶部</span>
    </div>
</body>
<script>
    let backTopEle = document.querySelector(".back-top");
    // 给文档绑定页面滚动事件
    document.addEventListener("scroll", function () {
        // 获取页面卷上去的高度scrollTop
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop > 50) {
            // 显示回到顶部操作，删除hide类名
            backTopEle.classList.remove("hide");
        } else {
            // 隐藏
            backTopEle.classList.add("hide");
        };
    });
    // 点击回到顶部
    backTopEle.addEventListener("click", function () {
        document.documentElement.scrollTop = document.body.scrollTop = 0;
    });

    let imgEle = document.querySelector("img")
    // 悬浮换色
    backTopEle.addEventListener("mouseover", function () {
        imgEle.src = "./images/totop_hover.png";
    });

    // 鼠标离开
    backTopEle.addEventListener("mouseout", function () {
        imgEle.src = "./images/totop.png";
    });
</script>

</html>